<template>
	<view class="main">
		<view class="top">
			<view class="">入库验收</view>
			<view class="closeicon" @click="close"><uni-icons type="close" size="22"></uni-icons></view>
		</view>
		<view class="title">
			<view class="apply_id">
				<view class=""><input type="text" placeholder="输入条码/商品" /></view>
				<view class="seachbtn">搜索</view>
			</view>
		</view>
		<view class="good_detail">
			<view class="td_area">
				<view class="td td_1">商品名称</view>
				<view class="td td_2">规格说明</view>
				<view class="td td_3">条码</view>
				<view class="td td_4">数量/单位</view>
				<view class="td td_5">验收数</view>
				<view class="td td_6">验收情况</view>
				<view class="td td_7">操作</view>
			</view>
			<view class="tr_area" :class="{ select: index === SelectIndex }" v-for="(item, index) in goodDetail" :key="index" @click="clickItem(index)">
				<view class="tr tr_1">{{ item.goodName || '商品名称' }}</view>
				<view class="tr tr_2">{{ item.spec.specStr || '规格说明' }}</view>
				<view class="tr tr_3">{{ item.unit.barcode || '条码' }}</view>
				<view class="tr tr_4">{{ item.quantity }}/{{ item.unit.unitName || '单位' }}</view>
				<view class="tr tr_5">{{item.checkQuantity}}</view>
				<view class="tr tr_6" :style="{ color: stutsStyle(item) }">
					{{ item.CheckDetailId ? item.CheckDetailId[0]?.checkStatus.label : '待验收' }}
				</view>
				<view class="tr tr_7">
					<view v-if="item.CheckDetailId.length === 0" class="sub_btn" @click="check(item)">验收</view>
					<view v-else class="sub_btn" @click="edit(item)">修改</view>
					<view class="sub_btn">查看</view>
				</view>
			</view>
		</view>

		<view class="btn_box">
			<view class="exit_btn" @click="close">退 出</view>
			<view class="submit_btn" @click="submit">提交验收单</view>
		</view>
		<uni-popup ref="popupCheck" type="center">
			<view class="popupCheck">
				<checkAccept :acceptItem="acceptItem" @close="checkAcceptClose" @success="checkSuccess"></checkAccept>
			</view>
		</uni-popup>
		<uni-popup ref="checkAcceptEdit" type="center">
			<view class="popupCheck">
				<checkAcceptEdit :acceptItem="acceptItem" @close="checkAcceptEditClose"></checkAcceptEdit>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import checkAccept from './checkAccept.vue';
import checkAcceptEdit from './checkAcceptEdit.vue';
const clouldDB = uniCloud.importObject('getDb');
	import {userMainStore} from'@/store/mainStore.js'
	const mainStore=userMainStore()

export default {
	name: 'storeInSure',

	components: {
		checkAccept,
		checkAcceptEdit
	},
	props: {
		applyForItem: {
			type: Object,
			default: () => {}
		}
	},

	data() {
		return {
			SelectIndex: -1,
			acceptItem: {}, //具体验收商品信息
			goodDetail: [],
			StatusMap: {
				normal: '#55aa00',
				abnormal: '#ff0000',
				quantityToo: '#aaff7f',
				quantityLess: '#ffaa7f'
			},
			checkDetailId: ''
		};
	},

	mounted() {
		this.initData();
		console.log('供应商',JSON.stringify(this.applyForItem));
	},
	methods: {
		async initData() {
			try {
				const res = await clouldDB.getApplyForGoodDetail(this.applyForItem.applyForId);
			
				if (res.code) {
										
			this.goodDetail=res.data.map(item=>({...item,checkQuantity:item.CheckDetailId?.length>0?item.CheckDetailId[0].totalQuantity:0}))
					
				
				} else {
					uni.showToast({
						title: '无数据' + e
					});
				}
			} catch (e) {
				console.log(e);
			}
		},
		checkAcceptState(item) {
			const isChecked = false; //是否已验收
			const isAudited = false; //是否已审核
		
		},

		checkAcceptClose() {
			this.$refs.popupCheck.close();
		},
		stutsStyle(item) {
			const statusValue = item.CheckDetailId ? item.CheckDetailId[0]?.checkStatus.value : '';

			switch (statusValue) {
				case 'ready':
				    return '#ccc'
				case 'normal':
					return '#52c41a'; // 成功绿色
				case 'quantityLess':
				case 'quantityToo':
					return '#faad14'; // 警告黄色
				case 'abnormal':
					return '#ff4d4f'; // 错误红色
				default:
					return '#ccc'; // 默认灰色
			}
		},

		async close() {
			this.$emit('close');
		},
		exit() {},

		checkSuccess(res) {
			console.log('11111111', JSON.stringify(res) );
		const hasindex=this.goodDetail.findIndex(item=>item.productId===res.productId)
          if(hasindex!==-1){
			 	this.goodDetail[hasindex] = { ...this.goodDetail[hasindex],checkQuantity:res.totalQuantity,CheckDetailId:[{checkStatus:res.checkStatus}]}; 
		  }
		

			console.log('验收成功通知', this.goodDetail.length);
		},
		checkAcceptEditClose() {
			this.$refs.checkAcceptEdit.close();
		},
		check(item) {
			this.SelectIndex = this.goodDetail.findIndex((i) => i.productId === item.productId);
			this.acceptItem = item;
			this.$refs.popupCheck.open();
		},
		clickItem(index) {
			this.SelectIndex = index;
		},
		edit(item) {
			console.table('商品具体商品明细', JSON.stringify(item));

			this.acceptItem = item;
			this.SelectIndex = this.goodDetail.findIndex((i) => i.productId === item.productIdtId);
			this.$refs.checkAcceptEdit.open();
		},
		async submit() {
			const db = uniCloud.databaseForJQL();
			console.log(this.goodDetail);
			// 1. 修正f为有效默认值（如null），并过滤无效ID
			const ids = this.goodDetail
				.map((item) => {
					// 确保CheckDetailId存在且是数组，且第一个元素有_id
					if (item.CheckDetailId && item.CheckDetailId.length > 0 && item.CheckDetailId[0]._id) {
						return item.CheckDetailId[0]._id;
					} else {
						return null; // 用null代替未定义的f
					}
				})
				.filter((id) => id !== null); // 过滤掉null，避免无效ID影响查询

			console.log('待查询的有效ID数组：', ids);

			// 2. 若ids为空，直接返回避免无效查询
			if (ids.length === 0) {
				console.log('没有有效ID可查询');
				return;
			}

			// 3. 使用db.command.in()查询多ID
			const cmd = db.command; // 获取命令对象
			const res = await db
				.collection('inventory_check_result')
				.where({
					_id: cmd.in(ids) // 正确语法：查询_id在ids数组中的文档
				})
				.get();
					console.log('查询结果：', res.data);
				const result=[]
				res.data.forEach(item=>{
					const {productId,spec}=item
					 item.checkDetails.forEach(detail => {
					            // 提取需要的字段并组合成新对象
					            const flattenedItem = {
					                productId: productId,
									spec:spec||{},
					                convertedQuantity: detail.convertedQuantity,
					                checkType: detail.checkType||"",
					                productionCode: detail.productionCode,
					                productionDate: detail.productionDate,
									batchNo:detail.batchNo
					            };
					            
					            // 添加到结果数组
					            result.push(flattenedItem);
					        });
					
					
				})
				
			
			  //扁平后的数组写入流水
			  const mainBody={
				  wareHouseId:mainStore.mainObject.id,
				  supplierId:this.applyForItem.supplier
				  
			  }
			  console.log("555555",JSON.stringify(mainBody));	
			  const action={
				  type:'add',
				  id:"",
				  name:'checkAccept'
				  }
			result.forEach(async (item)=>{
		const a=	await clouldDB.onInventoryFlow(mainBody,item,action)
				console.log(a);
			})	  
			 
			  
					
			
	
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	display: flex;
	flex-direction: column;
	border-radius: 8rpx;
	width: 100%;
}

.top {
	display: flex;
	position: relative;
	background-color: #ffffff;
	font-weight: 600;
	margin-bottom: 20rpx;
	width: 100%;
	height: 100rpx;
}
.popupCheck {
	height: auto;
	margin: 0 auto;
}

.title {
	display: flex;
	padding: 20rpx 40rpx;

	input {
		background-color: white;
		padding: 5rpx 5rpx;
		border: 1rpx solid #ddd;
		border-radius: 4rpx;
	}

	.apply_id {
		display: flex;
		margin: 0 50rpx;
		padding: 10rpx 20rpx;
	}

	.seachbtn {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #55aaff;
		color: white;
		padding: 0 20rpx;
		border-radius: 8rpx;
		margin-left: 20rpx;
		cursor: pointer;
	}
}

.td_area,
.tr_area {
	display: flex;
}

.td,
.tr {
	padding: 10rpx 20rpx;
	border-bottom: 1rpx solid #eee;
}

.td {
	background-color: #f0f0f0;
	font-weight: 500;
}

.td_1,
.tr_1 {
	width: 20%;
}
.td_2,
.tr_2 {
	width: 20%;
}
.td_3,
.tr_3 {
	width: 10%;
}
.td_4,
.tr_4 {
	width: 10%;
}
.td_5,
.tr_5 {
	width: 5%;
}
.td_6,
.tr_6 {
	
	width: 10%;
	
}
.td_7,
.tr_7{
	display: flex;
	gap: 20rpx;
	cursor: pointer;
	:active {
		color: #55aaff;
	}
	width: 20%;
}
.select {
	background-color: #55aaff;
	color: #ffffff;
}
.closeicon {
	position: absolute;
	right: 10rpx;
	top: 0;
	cursor: pointer;
}
.btn_box {
	margin-top: 50rpx;
	display: flex;
	align-items: center;
	justify-content: space-evenly;
}
.exit_btn {
	background-color: #ccc;
	border-radius: 8rpx;
	padding: 20rpx 20rpx;
}
.submit_btn {
	background-color: #55aaff;
	border-radius: 8rpx;
	padding: 20rpx 20rpx;
}
.sub_btn {
}
</style>
